<template>
  <MdEditor
    ref="mdEditor"
    :modelValue="value"
    :noImgZoomIn="false"
    :showToolbarName="true"
    :toolbars="toolbars"
    @onUploadImg="onUploadImg"
    @onChange="(editor) => emit('update:value', editor)"
    v-bind="$attrs"
  />
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted } from "vue";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import { Upload, UploadMinio } from "@/api/common";
const mdEditor = ref(null);
const { value, readOnly, preview } = defineProps({
  value: {
    type: String,
    default: "",
  },
  preview: {
    type: Boolean,
    default: false,
  },
  readOnly: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:value"]);

const toolbars = ref([
  "bold",
  "underline",
  "italic",
  "-",
  "title",
  "strikeThrough",
  "sub",
  "sup",
  "quote",
  "unorderedList",
  "orderedList",
  "task",
  "-",
  "codeRow",
  "code",
  "link",
  "image",
  "table",
  "mermaid",
  "katex",
  "-",
  "revoke",
  "next",
  "save",
  "=",
  "pageFullscreen",
  "fullscreen",
  "preview",
  "previewOnly",
  "htmlPreview",
  "catalog",
]);

const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
    files.map((file) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append("file", file);

        UploadMinio(form)
          .then((res) => rev(res))
          .catch((error) => rej(error));
      });
    })
  );
  callback(
    res.map((item) => {
      return item.data;
    })
  );
};
onMounted(() => {
  console.log(mdEditor.value, preview);
  if (preview) {
    mdEditor.value.togglePreviewOnly(true);
  }
});
</script>